import * as THREE from 'three';
import { Vec3 } from '@/core/types';
import { Entity } from './Entity';
import { EntityType, EntityData } from './types';
import { WorldManager } from '@/world/WorldManager';
import { ItemDropManager } from '@/world/ItemDrop';
import { Cow } from './Cow';
import { Pig } from './Pig';
import { Sheep } from './Sheep';
import { Zombie } from './Zombie';
import { Skeleton } from './Skeleton';

export class EntityManager {
  private entities: Map<string, Entity> = new Map();
  private scene: THREE.Scene;
  private worldManager: WorldManager;
  private itemDropManager?: ItemDropManager;
  private nextEntityId = 0;
  private spawnTimer = 0;
  private maxEntities = 50;

  constructor(scene: THREE.Scene, worldManager: WorldManager, itemDropManager?: ItemDropManager) {
    this.scene = scene;
    this.worldManager = worldManager;
    this.itemDropManager = itemDropManager;
  }

  public update(deltaTime: number, playerPosition: Vec3): void {
    // 更新所有实体
    for (const [id, entity] of this.entities) {
      // 向敌对生物提供玩家位置信息
      if (entity.getType() === EntityType.ZOMBIE || entity.getType() === EntityType.SKELETON) {
        (entity as any).updatePlayerPosition(playerPosition);
      }
      
      entity.update(deltaTime);
      
      // 移除死亡的实体
      if (!entity.isAlive() && entity.getAI()?.state === 'dead') {
        this.removeEntity(id);
      }
      
      // 移除距离玩家太远的实体
      const distance = entity.getDistanceTo(playerPosition);
      if (distance > 100) { // 100方块外的实体会被移除
        this.removeEntity(id);
      }
    }
    
    // 生物生成逻辑
    this.spawnTimer += deltaTime;
    if (this.spawnTimer >= 5.0 && this.entities.size < this.maxEntities) { // 每5秒尝试生成
      this.trySpawnEntity(playerPosition);
      this.spawnTimer = 0;
    }
  }

  private trySpawnEntity(playerPosition: Vec3): void {
    // 在玩家周围随机位置生成实体
    const spawnDistance = 20 + Math.random() * 30; // 20-50方块距离
    const angle = Math.random() * Math.PI * 2;
    
    const spawnPosition: Vec3 = {
      x: playerPosition.x + Math.cos(angle) * spawnDistance,
      y: playerPosition.y + 10, // 稍微高一点，让它们掉落到地面
      z: playerPosition.z + Math.sin(angle) * spawnDistance
    };
    
    // 根据时间和条件选择生物类型
    const isNightTime = this.isNightTime(); // 简化的夜晚检测
    
    let entityTypes: EntityType[];
    if (isNightTime && Math.random() < 0.3) { // 30%概率生成敌对生物
      entityTypes = [EntityType.ZOMBIE, EntityType.SKELETON];
    } else {
      entityTypes = [EntityType.COW, EntityType.PIG, EntityType.SHEEP];
    }
    
    const randomType = entityTypes[Math.floor(Math.random() * entityTypes.length)];
    this.spawnEntity(randomType, spawnPosition);
  }

  private isNightTime(): boolean {
    // 简化的夜晚检测 - 基于游戏时间
    // 在实际游戏中会基于游戏内的昼夜循环
    const gameTime = Date.now() / 1000; // 使用真实时间作为简化
    return Math.floor(gameTime / 30) % 2 === 1; // 每30秒切换一次昼夜
  }

  public spawnEntity(type: EntityType, position: Vec3): string | null {
    try {
      const id = this.generateEntityId();
      const entity = this.createEntity(id, type, position);
      
      if (entity) {
        this.entities.set(id, entity);
        
        // 将实体的网格添加到场景中
        const mesh = entity.getMesh();
        if (mesh) {
          this.scene.add(mesh);
        }
        
        return id;
      }
    } catch (error) {
      console.error('Failed to spawn entity:', error);
    }
    
    return null;
  }

  private createEntity(id: string, type: EntityType, position: Vec3): Entity | null {
    try {
      switch (type) {
        case EntityType.COW:
          return new Cow(id, position, this.worldManager, this.itemDropManager);
        case EntityType.PIG:
          return new Pig(id, position, this.worldManager, this.itemDropManager);
        case EntityType.SHEEP:
          return new Sheep(id, position, this.worldManager, this.itemDropManager);
        case EntityType.CHICKEN:
          // TODO: 实现鸡类
          console.log(`Chicken not implemented yet`);
          return null;
        case EntityType.ZOMBIE:
          return new Zombie(id, position, this.worldManager, this.itemDropManager);
        case EntityType.SKELETON:
          return new Skeleton(id, position, this.worldManager, this.itemDropManager);
        case EntityType.SPIDER:
          // TODO: 实现蜘蛛类
          console.log(`Spider not implemented yet`);
          return null;
        case EntityType.CREEPER:
          // TODO: 实现爬行者类
          console.log(`Creeper not implemented yet`);
          return null;
        default:
          console.warn(`Unknown entity type: ${type}`);
          return null;
      }
    } catch (error) {
      console.error(`Failed to create entity ${type}:`, error);
      return null;
    }
  }

  public removeEntity(id: string): boolean {
    const entity = this.entities.get(id);
    if (entity) {
      // 从场景中移除网格
      const mesh = entity.getMesh();
      if (mesh) {
        this.scene.remove(mesh);
      }
      
      // 清理实体资源
      entity.dispose();
      
      // 从管理器中移除
      this.entities.delete(id);
      
      return true;
    }
    
    return false;
  }

  public getEntity(id: string): Entity | undefined {
    return this.entities.get(id);
  }

  public getAllEntities(): Entity[] {
    return Array.from(this.entities.values());
  }

  public getEntitiesInRange(position: Vec3, range: number): Entity[] {
    const entitiesInRange: Entity[] = [];
    
    for (const entity of this.entities.values()) {
      const distance = entity.getDistanceTo(position);
      if (distance <= range) {
        entitiesInRange.push(entity);
      }
    }
    
    return entitiesInRange;
  }

  public getEntitiesByType(type: EntityType): Entity[] {
    return Array.from(this.entities.values()).filter(entity => entity.getType() === type);
  }

  private generateEntityId(): string {
    return `entity_${this.nextEntityId++}`;
  }

  public getEntityCount(): number {
    return this.entities.size;
  }

  public clear(): void {
    // 清理所有实体
    for (const id of this.entities.keys()) {
      this.removeEntity(id);
    }
  }

  // 保存和加载实体数据
  public serializeEntities(): EntityData[] {
    return Array.from(this.entities.values()).map(entity => entity.getData());
  }

  public deserializeEntities(entitiesData: EntityData[]): void {
    // 清理现有实体
    this.clear();
    
    // 重新创建实体
    for (const data of entitiesData) {
      const entity = this.createEntity(data.id, data.type, data.position);
      if (entity) {
        // 恢复实体状态
        entity.setPosition(data.position);
        entity.setVelocity(data.velocity);
        entity.setRotation(data.rotation);
        entity.takeDamage(entity.getMaxHealth() - data.health); // 设置健康值
        
        this.entities.set(data.id, entity);
        
        const mesh = entity.getMesh();
        if (mesh) {
          this.scene.add(mesh);
        }
      }
    }
  }

  // 调试信息
  public getDebugInfo(): any {
    const entityCounts: Record<string, number> = {};
    
    for (const entity of this.entities.values()) {
      const type = entity.getType();
      entityCounts[type] = (entityCounts[type] || 0) + 1;
    }
    
    return {
      totalEntities: this.entities.size,
      maxEntities: this.maxEntities,
      entityCounts,
      spawnTimer: this.spawnTimer.toFixed(2)
    };
  }
}